package com.holdtime.jtt809dataservice.client.runnable;

import com.edata.common.BytesUtil;
import com.holdtime.jtt809dataservice.client.socket.TcpClient;
import com.holdtime.jtt809dataservice.common.NettyCommon;
import com.holdtime.jtt809dataservice.common.bean.ClientUpConnectReqDTO;
import io.netty.util.Attribute;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import protocol.jtt809.JTT809Packet;
import protocol.jtt809.ProtocolJT809;
import protocol.jtt809.body.UpConnectReq;

import java.util.concurrent.*;

/**
 * author: sunwei
 * Date: 2025/3/19 22:26
 * Description:
 */
@Slf4j
@Component
public class ClientScheduledService {

    ConcurrentHashMap<Object, ScheduledFuture<?>> clientUpConnectReqs = new ConcurrentHashMap<>();
    ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor();
    @Resource
    private ProtocolJT809 protocolJT809;

    /***
     * 连接上级平台
     * @param tcpClient
     * @param clientUpConnectReqDTO
     */
    public void connectParentPlatform(TcpClient tcpClient, ClientUpConnectReqDTO clientUpConnectReqDTO) {
        //if (clientUpConnectReqs.get(clientUpConnectReqDTO.getJrm()) == null) {
            ScheduledFuture<?> schedule = executorService.scheduleAtFixedRate(() -> {
                if (tcpClient.isConnected()) {
                    UpConnectReq upConnectReq = new UpConnectReq();
                    upConnectReq.setUserid(clientUpConnectReqDTO.getUserId());
                    upConnectReq.setPassword(clientUpConnectReqDTO.getPassWord());
                    upConnectReq.setDownLinkIp(clientUpConnectReqDTO.getParentPlatfromIp());
                    upConnectReq.setDownLinkPort(clientUpConnectReqDTO.getParentPlatfromPort());
                    JTT809Packet<UpConnectReq> packet = protocolJT809.getPacket(upConnectReq, UpConnectReq.MSG_ID, clientUpConnectReqDTO.getJrm());
                    tcpClient.send(packet);
                    log.info("向接入码:{},上级平台发送主链路登陆请求消息:{}", clientUpConnectReqDTO.getJrm(), BytesUtil.changebytetohexstring(packet.array()));
                } else {
                    log.info("tcp未连接，不能想接入码:{},上级平台发送主链路登陆请求消息", clientUpConnectReqDTO.getJrm());
                }
            }, 2 * 1000, 5 * 1000, TimeUnit.MILLISECONDS);
            Attribute<String> attr = tcpClient.getChannel().attr(NettyCommon.clientNumberKey);
            String number = attr.get();
            if (number == null) {
                attr.set(String.valueOf(clientUpConnectReqDTO.getJrm()));
            }
            clientUpConnectReqs.put(clientUpConnectReqDTO.getJrm(), schedule);
        //}
    }

    public void removeClientUpConnectReqs(long jrm) {
        if (clientUpConnectReqs.get(jrm) != null) {
            clientUpConnectReqs.remove(jrm);
        }
    }

    public ScheduledFuture<?> getClientUpConnectReqs(long jrm) {
        return clientUpConnectReqs.get(jrm);
    }
}
